๐Ÿงฑ Constructors & Cloning

๐Ÿงฑ 1. What is a Constructor?

A constructor is a special method that gets called automatically when we create an object. It is used to initialize values.

โœ… Rules:

  • Has the same name as the class
  • No return type (not even void)
  • Called automatically when object is created

๐Ÿ”ง Real-Life Example:

๐ŸŽ“ Imagine you're making a Student ID card machine.

  • Whenever a new card is created, you must give the name and roll number.
  • The constructor is like the machine that automatically fills in these details when the card (object) is made.
  • Without a constructor, you'd get a blank card and have to fill it manually later (more work, more error chances).

โœ… Java Code Example:

class Student {
    String name;
    int roll;

    // Constructor
    Student(String n, int r) {
        name = n;
        roll = r;
    }

    void display() {
        System.out.println("Name: " + name + ", Roll: " + roll);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Deepak", 101); // Constructor runs
        s1.display();
    }
}
๐Ÿงพ Output:
Name: Deepak, Roll: 101

๐Ÿ”ข 2. Types of Constructors

Type Purpose
Non Parameterized Constructor No arguments, used to assign default values
Parameterized Constructor Takes parameters to assign custom values
Copy Constructor Makes a copy of another object

โœ… All 3 Examples Together:

class Student {
    String name;

    // 1. Default Constructor
    Student() {
        name = "Default Name";
    }

    // 2. Parameterized Constructor
    Student(String n) {
        name = n;
    }

    // 3. Copy Constructor
    Student(Student s) {
        name = s.name;
    }

    void show() {
        System.out.println("Name: " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();              // default
        Student s2 = new Student("Deepak");      // parameterized
        Student s3 = new Student(s2);            // copy

        s1.show();  // Default Name
        s2.show();  // Deepak
        s3.show();  // Deepak
    }
}

๐Ÿ”„ 3. Shallow Copy vs Deep Copy

Shallow vs Deep Copy

๐Ÿ”ง Real-Life Example:

๐Ÿฑ Imagine you're giving lunch (tiffin boxes) to two friends:

  • ๐ŸงŠ Shallow Copy = Both lunch boxes share the same food container.
    If one adds salt, the other also tastes it โ€” because the food is shared.
  • ๐Ÿฑ Deep Copy = Each lunch box has its own separate food container.
    If one adds salt, the other remains unchanged โ€” because they have different food inside.

๐Ÿ’ก In Java:
- Shallow Copy = Both objects point to the same memory for internal data.
- Deep Copy = New object is created with separate memory, fully independent.

๐Ÿ”น Shallow Copy Example (Java):

class Address {
    String city;
}

class Student {
    String name;
    Address address;
}

public class Main {
    public static void main(String[] args) {
        Address addr = new Address();
        addr.city = "Pune";

        Student s1 = new Student();
        s1.name = "Deepak";
        s1.address = addr;

        Student s2 = s1; // shallow copy (same reference)

        s2.address.city = "Mumbai";

        System.out.println(s1.address.city); // Output: Mumbai (changed for both)
    }
}
๐Ÿ“Œ Both s1 and s2 point to the same Address object.

๐Ÿ”น Deep Copy Example:

class Address {
    String city;

    Address(String c) {
        city = c;
    }

    // Copy Constructor
    Address(Address a) {
        city = a.city;
    }
}

class Student {
    String name;
    Address address;

    Student(String n, Address a) {
        name = n;
        address = new Address(a); // Deep copy
    }
}

public class Main {
    public static void main(String[] args) {
        Address addr1 = new Address("Pune");
        Student s1 = new Student("Deepak", addr1);

        Student s2 = new Student(s1.name, s1.address); // deep copy
        s2.address.city = "Delhi";

        System.out.println(s1.address.city); // Pune
        System.out.println(s2.address.city); // Delhi
    }
}
๐Ÿ“Œ Now s1 and s2 have separate address objects.

๐Ÿงฌ 4. Cloning

Cloning means making an exact copy of an object using .clone() method.

โœ… Example:

class Student implements Cloneable {
    String name;

    Student(String name) {
        this.name = name;
    }

    // Clone method
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student s1 = new Student("Deepak");
        Student s2 = (Student) s1.clone(); // cloning s1 to s2

        System.out.println(s1.name); // Deepak
        System.out.println(s2.name); // Deepak
    }
}

๐Ÿ“Œ INTERVIEW-READY Summary

Concept Definition / Use
Constructor Auto-called method to initialize object
Default Constructor No parameters, assigns default values
Parameterized Constructor Accepts arguments to set values
Copy Constructor Creates object by copying another
Shallow Copy Copies object but shares same inner object reference
Deep Copy Creates full independent copy of object and inner object
Cloning Uses clone() to make exact copy (needs Cloneable interface)

๐Ÿง  Interview Questions

Question Answer
What is a constructor in Java? A special method called during object creation to initialize values.
Can a constructor return a value? No, constructors have no return type.
What is the difference between constructor and method? Constructor initializes object; method performs actions.
What is a copy constructor? A constructor that takes an object and copies its data.
What is shallow copy? Object copy where inner objects are shared.
What is deep copy? Object copy with all inner objects independently copied.
What is cloning? Making a copy using clone() method.
What is the need for Cloneable interface? Java requires it for safe cloning; else throws error.